package org.jef.socket.thread;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import org.jef.socket.event.EventType;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @version 1.0
 * @description: 分布式倒计时工具
 * 1、开始倒计时(1)，由各实例自身维护，先查询数据库
 * 2、暂停倒计时(2)，由接受到http请求的实例通过redis转发到其他实例,各个实例接受到请求后，发现有在运行的则将线程停止，并将当前倒计时写入数据库，如果没有则忽略
 * 3、重置倒计时(3)，由接收到http请求的实例将数据库剩余时间修改。并调用暂停
 * @author: ChengZhi 0336
 * @create: 2024-09-13 17:26
 **/
public class JefCountDownUtils {

    /**
     * 暂停状态
     */
    public static final String PAUSE_STATE = "2";

    /**
     * 重置状态
     */
    public static final String RESET_STATE = "3";

    /**
     * 开始
     * @param runnable   线程主体内容
     */
    public static void start(String key, Funcable runnable) {

        SingletonThreadPool.executeTask(key,runnable);
    }

    /**
     * 开始
     * @param runnable   线程主体内容
     */
    public static void start(String key, Runnable runnable) {

        SingletonThreadPool.executeTask(key, runnable);
    }

    /**
     * 暂停
     */
    public static void pause(String key) {
        StringRedisTemplate template = SpringUtil.getBean(StringRedisTemplate.class);
        CountDownMsg countDownMsg = new CountDownMsg();
        countDownMsg.setMsg(key);
        countDownMsg.setType(PAUSE_STATE);
        template.convertAndSend(EventType.TOPIC_COUNTDOWN.getValue(), JSON.toJSONString(countDownMsg));
    }

    /**
     * 重置
     */
    public static void reset(String key) {
        StringRedisTemplate template = SpringUtil.getBean(StringRedisTemplate.class);
        CountDownMsg countDownMsg = new CountDownMsg();
        countDownMsg.setMsg(key);
        countDownMsg.setType(RESET_STATE);
        template.convertAndSend(EventType.TOPIC_COUNTDOWN.getValue(), JSON.toJSONString(countDownMsg));
    }

}
